package org.dromara.chicken.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.AuditDto;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.erp.domain.ErpGoodsInOutInfo;
import org.dromara.erp.domain.ErpProducts;
import org.dromara.erp.mapper.ErpGoodsInOutInfoMapper;
import org.dromara.erp.mapper.ErpProductsMapper;
import org.dromara.chicken.domain.ChickenFeedOut;
import org.dromara.chicken.domain.ChickenFeedOutInfo;
import org.dromara.chicken.mapper.ChickenFeedOutInfoMapper;
import org.dromara.chicken.mapper.ChickenFeedOutMapper;
import org.dromara.chicken.service.IChickenFeedOutService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 鸡场投喂Service业务层处理
 *
 * @author Mr Lei
 * @date 2024-05-29
 */
@RequiredArgsConstructor
@Service
public class ChickenFeedOutServiceImpl implements IChickenFeedOutService {

    private final ChickenFeedOutMapper baseMapper;
    private final ChickenFeedOutInfoMapper infoMapper;
    private final ErpProductsMapper productsMapper;
    private final ErpGoodsInOutInfoMapper goodsInOutInfoMapper;

    /**
     * 查询鸡场投喂
     */
    @Override
    public ChickenFeedOut queryById(Long id) {
        //查询主表
        ChickenFeedOut chickenFeedOut = baseMapper.findById(id);
        //查询子表
        List<ChickenFeedOutInfo> infoList = infoMapper.findByMainId(id);
        chickenFeedOut.setContentInfo(infoList);
        return chickenFeedOut;
    }

    /**
     * 查询鸡场投喂列表，若依原写法
     */
    @Override
    public TableDataInfo<ChickenFeedOut> queryPageList(ChickenFeedOut bo, PageQuery pageQuery) {
        Page<ChickenFeedOut> result = baseMapper.queryPageList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }


    /**
     * 查询鸡场投喂列表
     */
    @Override
    public List<ChickenFeedOut> queryList(ChickenFeedOut bo) {
        LambdaQueryWrapper<ChickenFeedOut> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<ChickenFeedOut> buildQueryWrapper(ChickenFeedOut bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ChickenFeedOut> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getOrderNo()), ChickenFeedOut::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getChickenHatchId() != null, ChickenFeedOut::getChickenHatchId, bo.getChickenHatchId());
        lqw.eq(bo.getChickenHouseId() != null, ChickenFeedOut::getChickenHouseId, bo.getChickenHouseId());
        lqw.eq(bo.getAuditStatus() != null, ChickenFeedOut::getAuditStatus, bo.getAuditStatus());
        return lqw;
    }

    /**
     * 新增鸡场投喂
     */
    @Transactional(propagation = Propagation.NESTED)
    public Boolean insertByBo(ChickenFeedOut bo) {
        //新增主表数据
        validEntityBeforeSave(bo);
        boolean flag = baseMapper.insert(bo) > 0;
        if (flag) {
            //增加成功后设置回显ID
            bo.setId(bo.getId());
            //通过主表返回的ID遍历list子表
            List<ChickenFeedOutInfo> infoList = bo.getContentInfo();
            infoList.forEach(x -> {
                //设置子表的关联字段
                x.setOrderId(bo.getId());
                //执行子表新增
                infoMapper.addByBo(x);
            });
        }
        return flag;
    }

    /**
     * 修改鸡场投喂
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Boolean updateByBo(ChickenFeedOut bo) {
        //修改主表
        validEntityBeforeSave(bo);
        //修改子表
        List<ChickenFeedOutInfo> infoList = bo.getContentInfo();
        infoList.forEach(x -> {
            x.setOrderId(bo.getId());
            if (x.getId() == null) {
                //如果有新增子表，则调用新增的方法
                infoMapper.addByBo(x);
            }
            //其他原有的则执行编辑
            infoMapper.updateById(x);
        });
        return baseMapper.updateById(bo) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ChickenFeedOut entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 删除鸡场投喂
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
//        if (ids == null || (isValid && shouldCheckAuditStatus(ids))) {
//            // 如果id为空，或者isValid为true且审核通过的表不能删除，则返回false
//            return false;
//        }
        //查找出对应的子表
        LambdaQueryWrapper<ChickenFeedOutInfo> wrapper = new LambdaQueryWrapper<>();
        //主表用id则用wrapper.eq，主表是ids则用wrapper.in
        wrapper.in(ChickenFeedOutInfo::getOrderId, ids);
        //删除子表数据
        infoMapper.delete(wrapper);
        //删除主表数据
        return baseMapper.deleteBatchIds(ids) >0;
    }

    /*默认标题*/
    @Override
    public String defaultTitle(String formatDate) {
        Integer totalNum = baseMapper.selectByDateCunt(formatDate);
        //最低3位数，不足前面用0填充
        String format = String.format("%03d", totalNum);
        //拼接成新的标题
        return format;
    }

    /*审核操作*/
    @Override
    public void updateAudit(AuditDto dto) {
        LambdaUpdateWrapper<ChickenFeedOut> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ChickenFeedOut::getId, dto.getId());//设置更新条件
        updateWrapper.set(ChickenFeedOut::getAuditStatus, dto.getAuditStatus());//设置更新字段
        updateWrapper.set(ChickenFeedOut::getAuditRemark, dto.getAuditRemark());//设置更新字段
        updateWrapper.set(ChickenFeedOut::getAuditTime, new Date());//设置时间
        //根据审核表的id去查询主表明细
        ChickenFeedOut food = baseMapper.findById(dto.getId());
        //如果审核通过或单据作废执行
        if(dto.getAuditStatus() == 2 || dto.getAuditStatus() == 4){
            //如果单据已审核，则无法再次审核
            if(dto.getAuditStatus().equals(food.getAuditStatus())){
                //抛出异常
                throw new RuntimeException("单据已审核，不能再进行同样的操作");
            }
            //根据order_id查询ChickenFeedOutInfo表
            List<ChickenFeedOutInfo> contentInfo = infoMapper.findByMainId(dto.getId());
            //TODO 这里应该做库存大于0的校验
            contentInfo.forEach(o->{
                //查询erp_products表
                ErpProducts goods = productsMapper.findById(o.getProductId());
                //根据info列表遍历出来后，更新erp_products表的stock字段
                ErpProducts product = new ErpProducts();
                //把主表的order名称和模块名设置到erp_goods_in_out_info表的相关字段
                ErpGoodsInOutInfo goodsInfo = new ErpGoodsInOutInfo();
                //审核通过执行-减库存
                if(dto.getAuditStatus() == 2){
                    product.setStock(goods.getStock().subtract(o.getFoodNum()));
                    //设置说明
                    goodsInfo.setRemark(food.getRemark());
                }else{
                    //作废执行-加库存
                    product.setStock(goods.getStock().add(o.getFoodNum()));
                    goodsInfo.setRemark("单据作废");
                }
                //设置更新商品的ID
                product.setId(o.getProductId());
                //执行erp_products的更新方法
                productsMapper.updateById(product);
                //设置商品ID
                goodsInfo.setGoodsId(o.getProductId());
                //设置模块名称
                goodsInfo.setModuleName("鸡场投喂");
                //设置订单名称
                goodsInfo.setOrderName(food.getOrderNo());
                //设置分类
                goodsInfo.setCateId(o.getProductsCateId());
                //TODO 设置规格,这里出库是以商品基本包装单位为准，所以不需要做多计量计算
                goodsInfo.setGoodsSpecId(goods.getUnitId());
                //变更后的新库存
                goodsInfo.setStock(product.getStock());
                //设置数量
                goodsInfo.setAmount(o.getFoodNum());
                //设置单价
                goodsInfo.setPrice(o.getUnitPrice());
                //设置金额
                goodsInfo.setMoney(o.getMoney());
                //执行erp_goods_in_out_info添加方法
                goodsInOutInfoMapper.insert(goodsInfo);
            });
        }
        //执行主表的更新方法
        baseMapper.update(updateWrapper);
    }


    // 这是一个辅助方法，用于检查auditStatus是否为2（已审核通过的表）
    private boolean shouldCheckAuditStatus(Collection<Long> ids) {
        LambdaQueryWrapper<ChickenFeedOut> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ChickenFeedOut::getId, ids); // 假设使用getId方法获取主键，而不是getAuditStatus
        lqw.eq(ChickenFeedOut::getAuditStatus, 2);
        ChickenFeedOut record = baseMapper.selectOne(lqw);
        return record != null;
    }
}
